package com.kly.user.serviceImpl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.db.dao.UserAlbumsContentDao;
import com.kly.user.db.dao.UserAlbumsDao;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.UserAlbumsContentEntity;
import com.kly.user.db.entity.UserAlbumsEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.dto.chatter.request.ChangeImageReq;
import com.kly.user.dto.chatter.response.ImagesDto;
import com.kly.user.enums.AlbumsStatus;
import com.kly.user.enums.AlbumsType;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.ImageOpTypeEnum;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.mapper.UserAlbumsContentMapper;
import com.kly.user.service.UserAlbumsContentService;
import com.kly.user.utils.ImagePrefixUtils;
import com.kly.user.utils.UserSnowflake;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("userAlbumsContentService")
public class UserAlbumsContentServiceImpl implements UserAlbumsContentService {
    @Resource
    UserAlbumsContentDao userAlbumsContentDao;
    @Resource
    UserAlbumsContentMapper mapper;
    @Resource
    AsyncEventBus pushEventBus;
    @Resource
    UserAlbumsDao userAlbumsDao;
    @Resource
    UserDao userDao;
    @Override
    public List<ImagesDto> getPrivateContent(String userCode, Integer albumsType) {
        List<UserAlbumsContentEntity> albumsContents =
                userAlbumsContentDao.selectByUserCode(userCode, albumsType);
        if (CollUtil.isNotEmpty(albumsContents)) {
            final List<ImagesDto> imagesDtos = albumsContents.stream().map(mapper::toImagesDto).collect(Collectors.toList());
            for (ImagesDto dto : imagesDtos) {
                dto.setImageUrl(getImageUrl(dto.getImageUrl()));
            }
            return imagesDtos;
        } else {
            return null;
        }
    }

    /**
     * 照片更改：只针对用户上传的个人照片操作， 且不涉及私密照片的操作
     */
    @Override
    public Response<ImagesDto> changeImage(ChangeImageReq changeImageReq) {
        ImagesDto returnDto = new ImagesDto();
        if (ImageOpTypeEnum.upload.equals(changeImageReq.getOpType())) {
            // 获取相册
            UserAlbumsEntity userAlbums = getUserPersonalAlbums(changeImageReq);
            // 保存照片
            UserAlbumsContentEntity userAlbumsContent = addNewImage(changeImageReq, userAlbums, userAlbums.getType());

            returnDto = getImagesDto(userAlbumsContent.getImageCode(), userAlbumsContent.getImageUrl());

        } else if (ImageOpTypeEnum.change.equals(changeImageReq.getOpType())) {
            final UserAlbumsContentEntity albumsContent = userAlbumsContentDao.selectByImageCode(changeImageReq.getImageCode());
            albumsContent.setImageUrl(changeImageReq.getImageUrl());
            // 修改
            userAlbumsContentDao.updateByPrimaryKey(albumsContent);
            // 通知客户端
            saveAsAvatar(changeImageReq.getUserCode(), changeImageReq.getImageUrl(), changeImageReq.getAvatarFlag());

            returnDto = getImagesDto(changeImageReq.getImageCode(), changeImageReq.getImageUrl());

        } else if (ImageOpTypeEnum.remove.equals(changeImageReq.getOpType())) {
            userAlbumsContentDao.deleteByImageCode(changeImageReq.getImageCode());
            returnDto = getImagesDto(changeImageReq.getImageCode(), changeImageReq.getImageUrl());
        }
        return Response.ok(returnDto);
    }


    private void saveAsAvatar(String userCode, String imageUrl, Integer avatarFlag) {
        // 所上传的照片为头像
        if (avatarFlag == 0) {
            return;
        }
        final UserEntity user = userDao.selectByUserCode(userCode);
        if (user == null) {
            return;
        }
        user.setAvatarUrl(imageUrl);
        userDao.updateByPrimaryKey(user);

        // 头像修改成功通知客户端进行更新
//        pushEventBus.post(buildEvent(userCode, AppEnum.MEBOO));

    }

    private Event buildEvent(String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.AVATAR_CHANGE.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).toUserCode(toUserCode).app(appEnum).content(JSONObject.toJSONString(params)).build();
    }

    @NotNull
    private ImagesDto getImagesDto(String imageCode, String imageUrl) {
        ImagesDto returnDto = new ImagesDto();
        returnDto.setImageCode(imageCode);
        returnDto.setImageUrl(imageUrl);
        return returnDto;
    }

    @NotNull
    private UserAlbumsContentEntity addNewImage(ChangeImageReq changeImageReq, UserAlbumsEntity userAlbums, Integer albumsType) {
        UserAlbumsContentEntity userAlbumsContent = new UserAlbumsContentEntity();
        userAlbumsContent.setType(changeImageReq.getImageType().getType());
        userAlbumsContent.setAlbumType(albumsType);
        userAlbumsContent.setVideoLength(changeImageReq.getVideoLength());
        userAlbumsContent.setStatus(1);
        userAlbumsContent.setAlbumCode(userAlbums.getAlbumCode());
        userAlbumsContent.setImageCode(String.valueOf(UserSnowflake.getInstance().nextId()));
        userAlbumsContent.setImageUrl(changeImageReq.getImageUrl());
        userAlbumsContentDao.insert(userAlbumsContent);

        saveAsAvatar(changeImageReq.getUserCode(), changeImageReq.getImageUrl(), changeImageReq.getAvatarFlag());
        return userAlbumsContent;
    }

    private UserAlbumsEntity getUserPersonalAlbums(ChangeImageReq changeImageReq) {
        UserAlbumsEntity userAlbums = userAlbumsDao.selectByType(changeImageReq.getUserCode(), AlbumsType.PERSONAL_ALBUMS.getType());
        if (Objects.isNull(userAlbums)) {
            userAlbums = createAlbums(changeImageReq);
        }
        return userAlbums;
    }

    private UserAlbumsEntity createAlbums(ChangeImageReq changeImageReq) {
        UserAlbumsEntity entity = new UserAlbumsEntity();
        entity.setAlbumCode(String.valueOf(UserSnowflake.getInstance().nextId()));
        entity.setStatus(AlbumsStatus.ACTIVE.getType());
        entity.setUserCode(changeImageReq.getUserCode());
        entity.setType(AlbumsType.PERSONAL_ALBUMS.getType());
        userAlbumsDao.insert(entity);
        return entity;
    }

    @Override
    public List<ImagesDto> getPrivateContent(Map<String, Object> prams) {
        List<UserAlbumsContentEntity> albumsContents =
                userAlbumsContentDao.selectByUserCodeAndImageCode(prams);
        if (CollUtil.isNotEmpty(albumsContents)) {
            final List<ImagesDto> imagesDtos = albumsContents.stream().map(albumsContent ->
                    {
                        ImagesDto imagesDto = mapper.toImagesDto(albumsContent);
                        imagesDto.setSendFlag(albumsContent.getStatus() > 0);
                        return imagesDto;
                    }
            ).collect(Collectors.toList());
            for (ImagesDto dto : imagesDtos) {
                dto.setImageUrl(getImageUrl(dto.getImageUrl()));
            }
            return imagesDtos;
        } else {
            return null;
        }
    }


    private String getImageUrl(String url) {
        String imageUrl = ImagePrefixUtils.getFullImageUrl(url);
        if(imageUrl.contains("video")){
            imageUrl = imageUrl+".mp4";
        }
        return imageUrl;
    }

    private String removePrefix(String url) {
        return ImagePrefixUtils.removePrefix(url);
    }

    @Override
    public Response<ImagesDto> getByUrl(String imageUrl) {
        if (StringUtils.isBlank(imageUrl)) {
            return Response.ok();
        }

        imageUrl = removePrefix(imageUrl);
        if (StringUtils.isBlank(imageUrl)) {
            return Response.ok();
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("imageUrl", imageUrl);
        final List<UserAlbumsContentEntity> userImages = userAlbumsContentDao.selectByParams(params);

        if (CollectionUtils.isEmpty(userImages)) {
            return Response.ok();
        }

        ImagesDto imagesDto = new ImagesDto();
        imagesDto.setImageUrl(userImages.get(0).getImageUrl());
        imagesDto.setImageCode(userImages.get(0).getImageCode());
        return Response.ok(imagesDto);
    }
}
